package chatBot.controller;

import chatBot.entity.Conversation;
import chatBot.service.ChatgptService;
import chatBot.service.ConversationService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/gpt")
@Api(tags = "ChatGPT 提问功能")

public class ChatgptController {

    @Autowired
    ConversationService conversationService;

    @Resource
    ChatgptService chatgptService;
    /**
     * ChatGPT流式对话接口
     * @param map 发送消息参数 {useToken、conversationId、prompt}
     * @return SseEmitter流
     */
    @PostMapping(path = "/chat", produces = "text/event-stream;charset=utf-8")
    public SseEmitter sendMsg(@RequestBody Map<String, Object> map) {

        Long conversationId = null;
        if (map.containsKey("conversationId")) {

            Object conversationIdObj = map.get("conversationId");
            if (conversationIdObj instanceof String) {
                conversationId = Long.parseLong((String) conversationIdObj);
            } else if (conversationIdObj instanceof Number) {
                conversationId = ((Number) conversationIdObj).longValue();
            }
        }

        String prompt = (String) map.get("prompt");

        // 如果 conversationId 为空，创建一个新会话
        boolean isNewConversation = false;
        if (conversationId == null) {
            Conversation conversation = new Conversation();
            conversation.setConversationName(prompt);
            conversationId = conversationService.createConversation(conversation);
            isNewConversation = true;
        }
        // 调用服务方法处理 GPT 请求
        return chatgptService.sendMsgSse(conversationId, prompt, isNewConversation);
    }




}
